"""
简化的系统配置管理
Simplified System Configuration Management
"""
import os
from typing import List, Dict, Any
from pathlib import Path

# 获取项目根目录
BASE_DIR = Path(__file__).parent.parent


class Settings:
    """简化的应用配置类"""
    
    # ==================== 基础配置 ====================
    APP_NAME: str = "简化校园数字孪生系统"
    VERSION: str = "2.0.0"
    API_PREFIX: str = "/api/v1"
    DEBUG: bool = os.getenv("DEBUG", "false").lower() == "true"
    
    # ==================== 数据库配置 ====================
    DATABASE_URL: str = os.getenv(
        "DATABASE_URL", 
        f"sqlite:///{BASE_DIR}/data/campus_twin.db"
    )
    
    # ==================== WVP集成配置 ====================
    WVP_BASE_URL: str = os.getenv("WVP_BASE_URL", "http://localhost:18080")
    WVP_API_KEY: str = os.getenv("WVP_API_KEY", "")
    WVP_USERNAME: str = os.getenv("WVP_USERNAME", "admin")
    WVP_PASSWORD: str = os.getenv("WVP_PASSWORD", "admin")
    
    # ==================== 服务器配置 ====================
    HOST: str = os.getenv("HOST", "0.0.0.0")
    PORT: int = int(os.getenv("PORT", "8001"))
    
    # ==================== CORS配置 ====================
    CORS_ORIGINS: List[str] = [
        "http://localhost:3000",
        "http://localhost:8080", 
        "http://127.0.0.1:3000",
        "http://127.0.0.1:8080",
        "http://localhost:80",
        "http://127.0.0.1:80",
        "http://localhost",
        "http://127.0.0.1",
        "null",  # 支持本地文件访问
        "*"  # 开发环境允许所有来源
    ]
    
    # ==================== 日志配置 ====================
    LOG_LEVEL: str = os.getenv("LOG_LEVEL", "INFO")
    LOG_FILE: str = str(BASE_DIR / "logs" / "app.log")
    LOG_FORMAT: str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    LOG_MAX_SIZE: int = 10 * 1024 * 1024  # 10MB
    LOG_BACKUP_COUNT: int = 5
    
    # ==================== AI服务配置 ====================
    AI_MODEL_PATH: str = str(BASE_DIR / "models")
    AI_MAX_WORKERS: int = int(os.getenv("AI_MAX_WORKERS", "2"))
    AI_TIMEOUT: float = float(os.getenv("AI_TIMEOUT", "30.0"))
    
    # AI服务启用配置
    AI_SERVICES_ENABLED: Dict[str, bool] = {
        "behavior_monitoring": True,
        "crowd_safety": True,
        "energy_management": True,
        "environment_hygiene": True,
        "classroom_quality": True,
        "teaching_assessment": True
    }
    
    # ==================== 视频流处理配置 ====================
    MAX_CONCURRENT_STREAMS: int = int(os.getenv("MAX_CONCURRENT_STREAMS", "10"))
    STREAM_TIMEOUT: int = int(os.getenv("STREAM_TIMEOUT", "30"))
    VIDEO_PROCESSING_FPS: int = int(os.getenv("VIDEO_PROCESSING_FPS", "2"))
    
    # ==================== 文件存储配置 ====================
    UPLOAD_DIR: str = str(BASE_DIR / "uploads")
    DATA_DIR: str = str(BASE_DIR / "data")
    LOGS_DIR: str = str(BASE_DIR / "logs")
    
    # ==================== 安全配置 ====================
    SECRET_KEY: str = os.getenv(
        "SECRET_KEY", 
        "simplified-campus-twin-secret-key-change-in-production"
    )
    
    # ==================== 性能配置 ====================
    # 简化的性能配置，移除复杂的自适应和监控配置
    MAX_REQUEST_SIZE: int = 50 * 1024 * 1024  # 50MB
    REQUEST_TIMEOUT: int = 60  # 60秒
    
    @classmethod
    def create_directories(cls):
        """创建必要的目录"""
        directories = [
            cls.DATA_DIR,
            cls.LOGS_DIR,
            cls.UPLOAD_DIR,
            cls.AI_MODEL_PATH
        ]
        
        for directory in directories:
            Path(directory).mkdir(parents=True, exist_ok=True)
    
    @classmethod
    def get_database_url(cls) -> str:
        """获取数据库连接URL"""
        return cls.DATABASE_URL
    
    @classmethod
    def get_wvp_config(cls) -> Dict[str, Any]:
        """获取WVP配置"""
        return {
            "base_url": cls.WVP_BASE_URL,
            "api_key": cls.WVP_API_KEY,
            "username": cls.WVP_USERNAME,
            "password": cls.WVP_PASSWORD
        }
    
    @classmethod
    def get_ai_config(cls) -> Dict[str, Any]:
        """获取AI服务配置"""
        return {
            "model_path": cls.AI_MODEL_PATH,
            "max_workers": cls.AI_MAX_WORKERS,
            "timeout": cls.AI_TIMEOUT,
            "services_enabled": cls.AI_SERVICES_ENABLED
        }
    
    @classmethod
    def get_video_config(cls) -> Dict[str, Any]:
        """获取视频处理配置"""
        return {
            "max_concurrent_streams": cls.MAX_CONCURRENT_STREAMS,
            "stream_timeout": cls.STREAM_TIMEOUT,
            "processing_fps": cls.VIDEO_PROCESSING_FPS
        }
    
    @classmethod
    def is_debug(cls) -> bool:
        """是否为调试模式"""
        return cls.DEBUG


# 创建全局配置实例
settings = Settings()

# 在导入时创建必要目录
settings.create_directories()


def get_settings() -> Settings:
    """获取配置实例"""
    return settings